/*
 * Read.cpp
 *
 *  Created on: 03/08/2011
 *      Author: jairo
 */

#include "bilbao/protocol/serial/Read.h"

namespace bilbao
{
	namespace protocol
	{
		namespace serial
		{
			Read::Read( void )
				: Thread(), _serialPort( 0 ), _filaComandos( 0 ), _stateRead()
			{
				// Do nothing
			}

			Read::Read( util::SerialPort* serialPort, SincronyzedQueue* filaComandos )
				: _serialPort( serialPort ), _filaComandos( filaComandos ), _stateRead( false )
			{
				// Do nothing
			}

			Read::~Read()
			{
				delete _serialPort;
				_serialPort = 0;

				delete _filaComandos;
				_filaComandos = 0;
			}

			void Read::run()
			{
				char ch = '\0';
				String buffer = "";
				int count;

				while ( true )
				{
					if ( _serialPort -> receive( &ch ) )
					{
						count = 0;

						if ( !_stateRead )
							_stateRead = true;

						buffer += ch;
					}
					else
					{
						if ( _stateRead )
						{
							++count;

							if ( count == 2 )
							{
								_filaComandos -> push( buffer );
								buffer.clear();
								_stateRead = false;
							}
							else
							{
								sleep( 50 );
							}
						}
					}
				}
			}
		} // namespace serial
	} // namespace protocol
} // namespace bilbao
